package com.config;

import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;

import javax.net.ssl.SSLContext;

@Configuration
public class Config {
    @Value("${trust-store}")
    private Resource trustStore;

    @Value("${trust-store-password}")
    private String trustStorePassword;

    @Value("${key-store}")
    private Resource keyStore;

    @Value("${key-store-password}")
    private String keyStorePassword;

    @Value("${key-password}")
    private String keyPassword;

    @Bean
    public SSLContext sslSocketFactory(){
        SSLContext sslContext = null;
        try {
            sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).
                            loadKeyMaterial(keyStore.getURL(), keyStorePassword.toCharArray(), keyPassword.toCharArray())
                    .build();
        } catch (Exception ex) {
            throw new RuntimeException("ssl configuration has problems.: " + ex.getMessage());
        }

        return sslContext;
    }
}
